package com.wedding.service;

import com.wedding.dao.MyPermissionMapper;
import com.wedding.dao.UserMapper;
import com.wedding.pojo.User;
import com.wedding.pojo.UserExample;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.acls.model.Permission;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MyPermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //相当配置文件中配置 <security:user name="tom" password="123" authorities="ROLE_SVIP"></security:user>
//        Integer id, String username, String password, Date birthday, String sex, String address, boolean accountnonexpired, boolean accountnonlocked, boolean credentialsnonexpired, boolean enabled, Collection<? extends GrantedAuthority > authorities
//        User u = new User(1,"tom","123",null,"男","北京",true,true,true,true,AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_PhoneUser"));
// 可以传多个角色 用逗号分隔 例如: "ROLE_SVIP,ROLE_VIP"
        /* User u = userMapper.selectByNamePassword(null);
        // Permission 自定义的一个pojo 对应权限表而不是角色表
        List<Permission> plist = null;//userMapper.findPermissionByName();
        List<GrantedAuthority> authorities = new ArrayList<>();
        for (Permission p : plist) {
            GrantedAuthority authority = new SimpleGrantedAuthority(p.getPattern());
            authorities.add(authority);
        }
        u.setAuthorities(authorities);
        */
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("ROLE_PhoneAdmin"));
        UserExample example = new UserExample();
        example.createCriteria().andUsernameEqualTo(username);
        User user = userMapper.selectByName(example);
        user.setAuthorities(authorities);
        return user;
    }

}
